from datetime import datetime
from utils.sql.app.user import get_userinfo
from utils.sql.app.record import insert_record, record_list, record_one, update_records


# 提交工天记录
async def record(data, user_id):
    try:
        add_calculate = await calculate(data.job_date, data.start_time, data.end_time, data.half_time, data.over_time,
                                        user_id)
        if add_calculate['code'] == 200:
            post_datas = {}
            post_datas.update(data)
            post_datas.update(add_calculate['data'])
            return insert_record(post_datas, user_id)
    except Exception as e:
        return {
            "code": 201,
            "data": e,
            "message": "添加失败"
        }


# 查询工天列表
async def one_record(id, user_id):
    return record_one(id, user_id)


# 查询单个工天
async def record_lists(year, month, current, user_id):
    return record_list(year, month, user_id, current)


# 修改单个工天
async def update_record(data, user_id):
    add_calculate = await calculate(data.job_date, data.start_time, data.end_time, data.half_time, data.over_time,
                                    user_id)
    if add_calculate['code'] == 200:
        post_datas = {}
        post_datas.update(data)
        post_datas.update(add_calculate['data'])
    return update_records(post_datas, user_id)


# 计算工时及薪资
async def calculate(job_date, start_time, end_time, half_time, over_time, user_id):
    try:
        user = get_userinfo(user_id)
        start = datetime.strptime(start_time, "%Y-%m-%d %H:%M")
        end = datetime.strptime(end_time, "%Y-%m-%d %H:%M")
        if user['code'] == 200:
            # 当日工时
            # 计算公式 (结束时间-开始时间).秒/3600秒-休息时间
            seconds = (end - start).seconds / 3600 - float(half_time)
            # 当日薪资
            # 计算公式 当日工时/整日工时*日薪
            money_day = float(seconds) / float(user['data'].day_manhour) * float(user['data'].daily_wage)
            # 加班费
            # 计算公式 加班时长*时薪
            overtime_pay = float(over_time) * float(user['data'].hourly_wage)
            # 每日工作天数
            # 计算公式 当日工时/整日工时
            working_days = float(seconds) / float(user['data'].day_manhour)
            return {
                "code": 200,
                "data": {
                    "man_hour": seconds,
                    "money_day": money_day,
                    "overtime_pay": overtime_pay,
                    "working_days": working_days
                },
                "message": "计算成功"
            }
    except Exception as e:
        return {
            "code": 201,
            "data": e,
            "message": "计算失败"
        }
